//
//  MovieDetail.swift
//  AppleDemo
//
//  Created by Just 花语 on 2025/10/28.
//


import SwiftUI
import SwiftData
struct MovieDetail:View{
    @Bindable var movie:Movie
    let isNew:Bool
    
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var context
    
    var sortedFriends:[FriendIn5]{
        movie.favoriteBy.sorted { first, second in
            first.name < second.name
        }
    }
    init(movie:Movie,isNew:Bool = false){
        self.movie = movie
        self.isNew = isNew
    }
    var body: some View{
        Form{
            TextField("Name",text: $movie.title)
                .autocorrectionDisabled()
            DatePicker("Release Date",selection: $movie.releaseDate,displayedComponents: .date)
            if !movie.favoriteBy.isEmpty{
                Section("Favorited by"){
                    ForEach(sortedFriends) { friend in
                        Text(friend.name)
                    }
                    .onDelete(perform: deleteFriendsSection)
                }
            }
        }
        .navigationTitle(isNew ? "New Movie":"Movie")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar{
            if isNew{
                ToolbarItem(placement: .confirmationAction) {
                   Button("Save") {
                       dismiss()
                   }
               }
                ToolbarItem(placement: .cancellationAction) {
                   Button("Cancel") {
                       context.delete(movie)
                       dismiss()
                   }
               }
            }
        }
    }
    private func deleteFriendsSection(at offsets: IndexSet){
        for index in offsets{
            let friend = sortedFriends[index]
            friend.favoriteMovie = nil
        }
        try? context.save()
    }
}
#Preview {
    NavigationStack{
        MovieDetail(movie: SampleData.shared.movie)
    }
}

